<template>
    <div class="rule-manage">
        <div class="query-form">
            <el-form ref="menuFormRef" inline :model="ruleSearch">
                <el-form-item label="角色名称:" prop="roleName">
                    <el-input v-model="ruleSearch.roleName" placeholder="请输入菜单管理"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="getRoleList" type="primary">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <div class="action">
                <el-button @click="add" v-HasPermission="'role-create'" type="primary">创建</el-button>
            </div>
            <el-table :data="tableData.data" style="width:100%;">
                <el-table-column v-for="item in tableData.columns" :key="item.prop" :prop="item.prop"
                    :label="item.label" :width="item.width">
                    <template #default="scope" v-if="item.render">
                        <span>{{item.render ? item.render(scope.row,scope.column) : ''}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300" align="center">
                    <template #default="scope">
                        <el-button type="primary" v-HasPermission="'role-edit'" @click="edit(scope.row)">编辑</el-button>
                        <el-button type="primary" v-HasPermission="'role-permission'" @click="setPermission(scope.row)">
                            设置权限</el-button>
                        <el-button type="danger" v-HasPermission="'role-delete'" @click="singleRemove(scope.row.id)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <Pagination :page="tableData.page" @change-size="changeSize" />
        </div>
        <!-- 编辑与新增 TO-DO -->
        <roleForm :show="show" :type="action" :title="formData.title" :roleFormData="formData.roleFormData"
            @close="close" @submit="submit"></roleForm>
        <powerForm :show="permissionData.powerShow" :data="permissionData.data" @submit="handleSubmit"
            @close="handleClose"></powerForm>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, computed } from 'vue'
import type { FormInstance } from "element-plus"
import { Columns } from "@/interface/common"
import { roleParams, RoleRow, PermissionList, RoleEditParams } from "@/interface/role"
import { Page } from "@/interface/common"
import { roleList, roleCreate, roleEdit, roleDelete, updatePermission, roleAllList } from "@/api/role"
import useCurrentInstance from "@/hook/useCurrentInstance"
import utils from "@/utils/utils.js"
import roleForm from './components/roleForm.vue'
import Pagination from "@/components/Pagination.vue"
import powerForm from './components/powerForm.vue'
import { useStore } from "vuex"

const store = useStore()
const menuList = computed(() => store.state.menuList)
onMounted(() => {
    console.log("菜单", menuList.value)
    getActionMap(menuList.value)
    getRoleList()
})
// 查询条件
const roleFormRef = ref<FormInstance>()
const ruleSearch = reactive<roleParams>({
    roleName: ""
})
const reset = () => {
    roleFormRef!.value?.resetFields()
}

const actionPromissionMap = ref({})
// 权限映射
const getActionMap = (list: any) => {
    let actionMap = {} as any
    console.log(list)
    console.log('类型', Object.prototype.toString.call(list))
    const deep = (arr: any) => {
        console.log("deep", arr)
        while (arr.length) {
            let item = arr.pop()
            if (item.children && item.action) {
                console.log(item.menuName)
                actionMap[item.menuId] = item.menuName;
            }
            if (item.children && !item.action) {
                deep(item.children);
            }
        }
    }
    deep(JSON.parse(JSON.stringify(list)))
    actionPromissionMap.value = actionMap
    console.log("打印列表", actionPromissionMap.value)
}



// 列表
const tableData = reactive<Columns>({
    data: [],
    columns: [
        {
            label: "角色名称",
            prop: "roleName",
            align: "center"
        },
        {
            label: '备注',
            prop: 'remark'
        },
        {
            label: '权限列表',
            prop: 'menuType',
            width: 200,
            render: (row, column) => {
                console.log('行数据', row.permissionList.halfCheckedKeys)
                let halfCheckedKeys = row.permissionList.halfCheckedKeys || []
                let names = [] as number[];
                console.log('映射对象', halfCheckedKeys)
                for (let i in halfCheckedKeys) {
                    let item = halfCheckedKeys[i]
                    let name = actionPromissionMap.value[item] as any
                    if (item && name) {
                        names.push(name)
                    }
                }
                return names.join(",")
            }
        },
        {
            label: '创建时间',
            prop: 'createdAt',
            render: (row, column) => {
                return utils.formateDate(new Date(row.createdAt))
            }
        },
    ],
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
    }
})
// 获取列表数据
const getRoleList = async () => {
    try {
        const { list, page } = await roleList({ roleName: ruleSearch.roleName, page: tableData.page as Page })
        console.log("数据", list);
        tableData.data = list
        tableData.page = page
    } catch (error) {
        console.error(error)
    }
}

const changeSize = (num: number) => {
    tableData.page!.pageNum = num
    getRoleList()
}

// 编辑与新增 TO-DO
const show = ref(false)
// 判断是编辑还是新增
const action = ref('add')
const formData = reactive({
    title: '创建菜单',
    roleFormData: {
        roleName: '',
        remark: '',
    }
})
//权限弹窗的数据
const permissionData = reactive({
    powerShow: false,
    data: {
        remark: "",
        roleName: ""
    }
})
// 创建
const add = () => {
    formData.title = "新建角色"
    action.value = 'add'
    show.value = true
}
// 编辑
const edit = (row: RoleRow) => {
    console.log("编辑  行数据", row)
    formData.title = "角色编辑"
    formData.roleFormData = row
    action.value = 'edit'
    show.value = true
}
// 设置权限
const setPermission = (row: RoleRow) => {
    console.log('设置权限', row, typeof row)

    permissionData.data = row
    console.log('权限数据', permissionData.data)
    permissionData.powerShow = true
}
// 删除
const singleRemove = async (id: number) => {
    console.log('删除的id', id)
    const res = await roleDelete({ id })
    that.$message.success("角色删除成功")
    getRoleList()
}
const { globalProperties: that } = useCurrentInstance()
const submit = async (data: RoleEditParams) => {
    console.log('提交的数据', data)
    const { roleName, id, remark } = data
    if (action.value === 'add') {
        const res = await roleCreate({ roleName, remark })
        that.$message.success("角色添加成功")
        getRoleList()
        return
    }
    const res = await roleEdit({ id, roleName, remark })
    that.$message.success("角色编辑成功")
    getRoleList()
}
const close = () => {
    show.value = false
    action.value = 'add'
}

// 保存权限设置
const handleSubmit = async (data: PermissionList) => {

    const { id, checkedKeys, halfCheckedKeys } = data
    console.log('参数', checkedKeys, halfCheckedKeys)
    const params = {
        id,
        permissionList: {
            checkedKeys,
            halfCheckedKeys
        }
    }
    await updatePermission(params)
    console.log('打印参数', params)
    that.$message.success("设置成功")
    handleClose()
    getRoleList()
}
const handleClose = () => {
    console.log('关闭')
    permissionData.powerShow = false
}
</script>
<style lang='scss' scoped>
.rule-manage {
    width: 100%;
}
</style>